<?php

namespace App\GatewayWorker;

use App\Enum\CodeEnum;
use App\Enum\WorkermanEnum;
use App\Services\WorkermanService;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;

class Events
{

    public static function onWorkerStart($businessWorker)
    {
    }

    public static function onConnect($client_id)
    {
        WorkermanService::sendResult($client_id,'onConnect');
    }

    public static function onWebSocketConnect($client_id, $data)
    {
    }

    /**
     * @param $client_id
     * param $message
     * 格式:
     * {
     *      'token'     => 'xxx',
     *      'method'    => '方法名'
     *      'data'      => {a:1,b:2}
     * }
     * @return void
     */

    public static function onMessage($client_id, $message)
    {
        $message = json_decode($message,true);

        if ( empty($message) )
        {
            // exception 1 数据格式不对
            WorkermanService::sendError($client_id,"需传JSON格式数据。".var_export($message,true),CodeEnum::PARAM_ERROR);

        }elseif( !isset($message['method']) || !isset($message['source']))
        {
            // exception 2,关键key未填写
            WorkermanService::sendError($client_id,"数据格式:{source=>'来源认证', 'method'=> '方法名'', data'=> {a:1,b:2}}",CodeEnum::PARAM_ERROR);

        }elseif(!method_exists(WorkermanService::class,$message['method']))
        {
            // exception 3.1, 方法名不存在
            WorkermanService::sendError($client_id,"方法不存在:".$message['method'],CodeEnum::PARAM_ERROR);

        }elseif(!in_array($message['source'], array_keys(WorkermanEnum::ROOM)))
        {
            // exception 3.2, source不存在
            WorkermanService::sendError($client_id,"source来源认证失败:".$message['source'],CodeEnum::PARAM_ERROR);

        }else{

            Gateway::joinGroup($client_id, WorkermanEnum::ROOM[$message['source']]);
//            self::_log($client_id,$message);
            $method = $message['method'];
            $result = WorkermanService::$method($client_id, $message);

            //统一回复
            if( $result !== false ) WorkermanService::sendResult($client_id,$message['method'],self::_formatResult($result));

        }
    }

    public static function onClose($client_id)
    {
//        self::_log($client_id);
    }
    private static function _log($client_id, $data=[]):void
    {
        $uid = Gateway::getUidByClientId($client_id);
        Log::notice('UID='.$uid. 'REQUEST DATA========>'.var_export($data,true));
    }

    private static function _formatResult($result)
    {
        if(empty($result)) $result = [];
        elseif( !is_array($result)) $result = ['result'=>$result];
        return $result;
    }
}
